package main.car;

import lombok.extern.slf4j.Slf4j;
import main.model.ElaModel;
import main.model.ElaRepository;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.openqa.selenium.WebDriver;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Scheduled;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;

//@Configuration
@Slf4j
public class Meeting {

    @Resource
    private ElaRepository repository;

    @Value("http://www.sae-china.org")
    private String baseUrl;

    @Resource
    private WebDriver driver;

//    @Scheduled(fixedDelay = 2000000)
    public void main() {
        driver.get(baseUrl + "/meeting/c72");
        Set<String> urls = new HashSet<>();
        Document document = Jsoup.parse(driver.getPageSource());
        Element element = document.selectFirst("div.pages > a:nth-last-child(2)");
        int totalPage = Integer.parseInt(element.text());
        System.out.println(totalPage);
        for (int i = 0; i < totalPage; i++) {
            if (i != 1) {
                driver.get(baseUrl + "/meeting/c72?page=" + i + 1);
                document = Jsoup.parse(driver.getPageSource());
            }
            Elements elements = document.select("body > div:nth-child(7) > div.main.fr.mt_20 > ul > li > a");
            for (Element e : elements) {
                urls.add(baseUrl + e.attr("href"));
            }
        }
        saveInfo(driver, urls);
    }

    private void saveInfo(WebDriver driver, Set<String> urls) {
        log.info("startAll... ==>{}", urls.size());
        Document document;
        Element element;
        int c = 0;
        ElaModel elaModel;
        for (String url : urls) {
            elaModel = new ElaModel();
            elaModel.setType(3);
            elaModel.setCreateTime(new Date());
            log.info("start...{} == >{}", url, c++);
            driver.get(url);
            document = Jsoup.parse(driver.getPageSource());
            //标题
            element = document.selectFirst("div.articletitle > h1");
            System.out.println(element.text());
            elaModel.setTitle(element.text());
            elaModel.setId(element.text().hashCode() ^ (element.text().hashCode() >> 16));
            //时间和来源
            element = document.selectFirst("div.articletitle > p");
            String[] timeAndSource = element.text().split(" ");
            System.out.println(element.text());
            elaModel.setTime(timeAndSource[0]);
            elaModel.setSource(timeAndSource[1]);
            //内容
            element = document.selectFirst("div.contentdiv.f_14.clr_3");
            elaModel.setContent(element.html());
            repository.save(elaModel);
        }
    }


}
